package com.fengxu.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;

// 群聊客户端s
public class GroupChatClient {

    private InetSocketAddress address;

    public GroupChatClient(InetSocketAddress address){
        this.address = address;
    }

    public void run() throws Exception{
        NioEventLoopGroup workGroup = new NioEventLoopGroup(1);

        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 向pipeline中添加String的解码器
                            ch.pipeline().addLast("decode",new StringDecoder());
                            // 向pipeline中添加String编码器
                            ch.pipeline().addLast("encode",new StringEncoder());
                            // 向pipeline中加入自己的业务处理器
                            ch.pipeline().addLast(new ClientHandler());
                        }
                    });
        } catch (Exception e) {
            System.out.println("出现异常!");
            workGroup.shutdownGracefully();
        }

        ChannelFuture channelFuture = bootstrap.connect(address.getHostString(), address.getPort()).sync();
        channelFuture.addListener(future -> {
            if(future.isSuccess()){
                System.out.println("连接服务器成功!");
            } else {
                System.out.println("连接服务器失败!");
            }
        });
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String msg = scanner.nextLine();
            channelFuture.channel().writeAndFlush(msg);
        }
        channelFuture.channel().closeFuture().sync();
    }

    private class ClientHandler extends SimpleChannelInboundHandler<String>{

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
            System.out.println("接受到服务器消息:"+msg);
        }
    }

    public static void main(String[] args) throws Exception {
        GroupChatClient client = new GroupChatClient(new InetSocketAddress("127.0.0.1",6666));
        client.run();
    }
}
